<template>
  <div class="container">
    <div>
      <el-row :gutter="20">
        <!-- <el-col :span="6">
          <el-form ref="form" :model="form">
            <el-form-item label="姓名：">
              <el-input v-model="person.name" style="width:200px"></el-input>
            </el-form-item>
          </el-form>
        </el-col> -->
        <!-- <el-col :span="6">
          <el-form ref="form" :model="form">
            <el-form-item label="所属组织名称：">
              <el-select v-model="person.client" placeholder @change="changeClientOptions">
                <el-option
                  v-for="item in person.clientList"
                  :key="item.CLIENT_NO"
                  :label="item.USERNAME"
                  :value="item.CLIENT_NO"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col> -->
        <el-col :span="7">
          <el-form ref="form" :model="form">
            <el-form-item label="单位名称：">
              <el-input
                v-model="person.name"
                placeholder="请输入单位名称"
                style="width: 150px"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-form ref="form" :model="form" style="float: left">
            <el-button size="mini" type="primary" @click="personQuery"
              >查 询</el-button
            >
            <el-button size="mini" type="warning" @click="exportExcel">导 出</el-button>
            <!-- <el-button size="mini" type="success" @click="handleAdd"
              >新 增</el-button
            > -->
            <!-- <el-button size="mini" type="primary" @click="handleAreaGPSAll"
              >地 图</el-button
            > -->
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table
      v-loading="loading"
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
      highlight-current-row
    >
      <el-table-column
        prop="UNITNAME"
        label="单位名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="AREANAME"
        label="负责区域"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="JSROADNUM"
        label="机扫道路数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="JSCARNUM"
        label="机扫车辆数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="RGROADNUM"
        label="人工道路数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="RGWORKERNUM"
        label="环卫工人数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="TOILETNUM"
        label="公厕数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="LJCARNUM"
        label="垃圾车辆数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="LJPOINTNUM"
        label="垃圾点位数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="STATIONNUM"
        label="转运站数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="FACTORYNUM"
        label="处理厂数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="BADNUM"
        label="黑名单对象数"
        align="center"
      ></el-table-column>
      <!-- "STATIONNUM":"7","FACTORYNUM":"7","BADNUM":"0"} -->
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <!-- <el-button type="text" @click="handleAreaGPS(scope.$index, scope.row)"
            >展示区域</el-button
          >
          <el-button
            type="text"
            @click="handleRoadInfo(scope.$index, scope.row)"
            >道路详情</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(scope.$index, scope.row)"
            style="color: red"
            >删除被考核单位</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>

    <!-- 弹出框 -->
    <el-dialog
      :title="addDialogTitle"
      :visible.sync="isVisibleEdit"
      width="50%"
      :modal="false"
    >
      <el-form ref="form" :model="form" label-width="120px" class="flex">
        <el-form-item label="被考核单位名称：" class="wid50">
          <el-input style="width: 207px;"
            v-model="form.UNITNAME"
            placeholder="请输入被考核单位名称"
          ></el-input>
        </el-form-item>

        <!-- <el-form-item label="所属组织："  v-if="this.addDialogTitle === '新增被考核单位信息'">
              <el-select v-model="form.CLIENT_NO" placeholder @change="changeClientOptions">
                <el-option
                  v-for="item in person.clientList"
                  :key="item.CLIENT_NO"
                  :label="item.USERNAME"
                  :value="item.CLIENT_NO"
                ></el-option>
              </el-select>
            </el-form-item> -->
            <el-form-item label="负责区域：">
              <el-select v-model="form.AREANAME" disabled>
                <el-option
                  v-for="item in areaBidList"
                  :key="item.LID"
                  :label="item.LNAME"
                  :value="item.LID"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="所属区域：">
              <el-select v-model="form.所属区域" placeholder clearable>
                <el-option
                  v-for="item in areaBidList"
                  :key="item.LID"
                  :label="item.LNAME"
                  :value="item.LID"
                ></el-option>
              </el-select>
            </el-form-item> -->
        <!-- <el-form-item label="开始日期：" class="wid50">
          <el-date-picker
            v-model="form.STARTDATE"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期：" class="wid50">
          <el-date-picker
            v-model="form.ENDDATE"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item> -->
      </el-form>
      <!-- <el-button type="text" @click="getLotGPS()"
            >编辑信息</el-button
          > -->
      <!-- <el-button style="padding: 0; border: 0">
        <el-upload
          action="/上传文件的接口"
          :on-change="onChange"
          :auto-upload="false"
          :show-file-list="false"
          accept=".xls, .xlsx"
          class="upload"
        >
          <el-button size="mini" type="success">导入经纬度信息</el-button>
        </el-upload>
      </el-button> -->

      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 批量设置道路弹出框 -->
    <el-dialog
      :title="addDialogTitle"
      :visible.sync="isVisibleRoad"
      width="50%"
      :modal="false"
    >
      <el-form ref="form" :model="form" label-width="100px" class="flex">
        <el-form-item label="道路：">
          <el-select v-model="form.arrROAD" multiple collapse-tags>
            <el-option
              v-for="item in person.roadList"
              :key="item.ID"
              :label="item.ROADNAME"
              :value="item.ID"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisibleRoad = false">取 消</el-button>
        <el-button type="primary" @click="saveRoad()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 道路详情弹出框 -->
    <el-dialog
      :title="addDialogTitle"
      :visible.sync="isVisibleRoadInfo"
      width="45%"
      :modal="false"
    >
      <!-- <el-form ref="form" :model="form" label-width="100px" class="flex">
        <el-form-item style="height: 10vw" label="道路："> -->
      <div class="box">
        <el-row>
          <el-col :span="5" v-for="tag in roadInfoList" :key="tag.ROADNAME"
            ><div style="margin: 15px 25px">
              {{ tag.ROADNAME }}
            </div></el-col
          >
        </el-row>
        <!-- <el-tag v-for="tag in roadInfoList" :key="tag.ROADNAME" >
              {{ tag.ROADNAME }}
            </el-tag> -->
      </div>
      <!-- </el-form-item>
      </el-form> -->

      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisibleRoadInfo = false">取 消</el-button>
        <el-button type="primary" @click="saveRoad()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 被考核单位展示 -->
    <el-dialog
      @open="dialogOpenMap"
      title="被考核单位展示"
      :visible.sync="isVisibleMapPlayback"
      width="50%"
      :before-close="dialogCloseMap"
    >
      <div style="width: 100%; height: 500px">
        <div style="width: 100%; height: 100%" id="mapDialog"></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogCloseMap">取 消</el-button>
        <!-- <el-button type="primary" @click="isVisibleMapPlayback = false"
          >确 定</el-button
        > -->
      </span>
    </el-dialog>
  </div>
</template>
<script>
import '@/assets/css/common.css'
// import { formatDate } from '@/common/js/date.js'
import export2Excel from '@/utils/exportExcel/index.js'
export default {
  data () {
    return {
      addDialogTitle: '',
      loading: false,
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      // 人员管理
      person: {
        LNAME: '',
        name: '',
        client: '',
        clientList: [],
        roadList: [],
        team: '',
        teamList: []
      },
      // 新增人员
      newPersonForm: {
        show: false,
        Name: '',
        Phone: '',
        SimCardNo: '',
        BirhDay: '',
        WorkDate: '',
        Sex: '男',
        WorkType: '',
        ClientNo: ''
      },
      tableData: [],
      originalData: [],
      areaList: [],
      personSettingForm: {
        show: false
      },
      roadInfoList: [],
      form: {},
      isVisibleEdit: false,
      isVisibleRoad: false,
      isVisibleRoadInfo: false,
      dataLotGPS: [],
      mapDialog: null,
      loadingDialog: false,
      isVisibleMapPlayback: false,
      dataViewport: [],
      areaBidList: [],
    }
  },
  created () {
    this.getlistdata();
  },
  methods: {
    async getlistdata () {
      var url = 'Assess/GetUnit_Assess?UNITNAME='
      const { data } = await this.$Http.get(url)
      this.originalData = data
      this.personQuery()
    },
    // 筛选信息
    personQuery () {
      this.currentPage = 1;
      this.tableData = this.originalData
      if (this.person.name) this.tableData = this.tableData.filter(item => item.UNITNAME.includes(this.person.name))
    },
    // 导出Excel
    exportExcel () {
      let excelName = '被考核单位'
      const tHeader = ['单位名称', '负责区域', '机扫道路数', '机扫车辆数', '人工道路数', '环卫工人数', 
      '公厕数', '垃圾车辆数', '垃圾点位数', '转运站数', '黑名单对象数']
      const filterVal = ['UNITNAME', 'AREANAME', 'JSROADNUM', 'JSCARNUM', 'RGROADNUM', 'RGWORKERNUM'
      , 'TOILETNUM', 'LJCARNUM', 'LJPOINTNUM', 'STATIONNUM', 'FACTORYNUM', 'BADNUM']
      export2Excel(tHeader, filterVal, this.tableData, excelName)
    },
    // 新增被考核单位
    handleAdd () {
      this.addDialogTitle = '新增被考核单位信息'
      //清空编辑框
      this.form = {}
      //展示窗口
      this.isVisibleEdit = true;
    },
    // 打开道路详情窗口
    handleRoadInfo (index, row) {
      this.form = Object.assign({}, row);
      // this.form.arrROAD = []
      this.addDialogTitle = '道路详情信息'
      this.getRoadListInfo()
    },
    // 打开道路编辑窗口
    handleRoad (index, row) {
      this.form = Object.assign({}, row);
      // this.form.arrROAD = []
      this.addDialogTitle = '批量设置道路'
      this.isVisibleRoad = true;
      this.getRoadList()
    },
    // 打开编辑窗口
    handleEdit (index, row) {
      this.form = Object.assign({}, row);
      this.addDialogTitle = '编辑被考核单位信息'
      this.isVisibleEdit = true;
    },
    // 点击保存，判断是新增还是编辑操作
    handleSubmit () {
      if (this.addDialogTitle == '新增被考核单位信息') {
        this.saveAdd()
      } else {
        this.saveEdit()
      }
    },
    // 批量编辑道路
    async saveRoad () {

      var str = '';
      this.form.arrROAD.forEach(element => {
        str = str + element + ','
      });
      str = str.substring(0, str.length - 1);
      this.form.ROADID = str

      var url = 'Worker/saveRoadLotPB?LID=' + this.form.LID + '&ROADID=' + this.form.ROADID
      const { data } = await this.$Http.get(url)
      if (data.IsSucess) {
        this.$message.success('新增成功');
        this.isVisibleRoad = false
        this.getlistdata()
      } else {
        this.$message.error('新增失败');
      }

    },
    // 新增保存
    async saveAdd () {
      // console.log(this.addform)
      this.$axios({
        url: 'Worker/saveLotPB',
        method: 'post',
        data: {
          LID: '-1',
          LNAME: this.form.LNAME,
          PARENT_NO: '00000',
          COMPANY: this.form.COMPANY,
          STARTDATE: this.form.STARTDATE,
          ENDDATE: this.form.ENDDATE,
        },

      }).then((res) => {
        console.log(this.data)
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('新增成功');
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('新增失败');
        }
      })

    },
    // 保存编辑
    async saveEdit () {
      var url = 'Assess/UpdateUnitName_Assess?UNITNAME=' + this.form.UNITNAME + '&CLIENT_NO='+ this.form.CLIENT_NO
      const { data } = await this.$Http.get(url)
      console.log(data)
      if (data.IsSucess) {
          this.$message.success('编辑成功');
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('编辑失败');
        }
      },
    // 保存编辑
    async saveEdit111 () {
      this.$axios({
        url: 'Worker/saveLotPB',
        method: 'post',
        data: {
          LID: this.form.LID,
          LNAME: this.form.LNAME,
          PARENT_NO: '00000',
          COMPANY: this.form.COMPANY,
          STARTDATE: this.form.STARTDATE,
          ENDDATE: this.form.ENDDATE,
        },

      }).then((res) => {
        console.log(this.data)
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('编辑成功');
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('编辑失败');
        }
      })
    },
    // 删除被考核单位信息
    async handleDelete (index, row) {
      const confirmResult = await this.$confirm('删除被考核单位信息会导致统计数据丢失，是否确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult == 'confirm') {
        const params = {
          LID: row.LID,
        }
        const { data } = await this.$Http.get('Worker/deleteLotPB', { params })
        if (data.IsSucess) {
          this.$message.success('删除成功')
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('删除失败');
        }
      } else {
        this.$message.info('取消删除')
        this.isVisibleEdit = false
      }

    },
    // 获取区域列表
    async getAreaList () {
      const areaData = await this.$Http.get('/DataListCompany/GetRoadByAreaApi?AreaName=' + this.personSettingForm.area)
      this.areaList = areaData.data
    },
    // 保存人员信息
    async savePerson () {
      const params = {
        ClientNo: this.personSettingForm.CLIENT_NO,
        Area: this.personSettingForm.area,
        StaffName: this.personSettingForm.name
      }
      await this.$Http.get('/DataListCompany/SaveStaffRoadApi', { params })
      this.personSettingForm.show = false
      // 刷新列表信息
      this.getlistdata()
      // console.log(data);
    },

    // 获取GPS
    async getAreaGPS (row) {
      var url = 'Worker/getLotGPSInfoPB?LID=' + row.LID
      let { data } = await this.$Http.get(url)
      row.dataLotGPS = data
    },
    handleAreaGPS (index, row) {
      console.log(row)
      // var url = 'Worker/getLotGPSInfoPB?LID=' + row.LID
      // let { data } = await this.$Http.get(url)
      var data = row.dataLotGPS;
      if (row.dataLotGPS.length > 0) {
        this.dataLotGPS = [row]
        this.isVisibleMapPlayback = true
      } else {
        this.$message({
          message: '未查找到【' + row.LNAME + '】工作区域',
          type: 'warning'
        })
      }
    },
    handleAreaGPSAll () {
      this.dataLotGPS = this.originalData;
      this.isVisibleMapPlayback = true
    },
    //区域展示
    dialogCloseMap () {
      this.dataViewport = []
      this.mapDialog.clearOverlays()
      this.isVisibleMapPlayback = false
    },
    dialogOpenMap () {
      setTimeout(() => {
        if (!this.mapDialog) {
          this.mapDialogShow()
        }
        this.dataLotGPS.forEach(element => {
          // 使用函数
          // let randomColor = ;
          // console.log(randomColor); // 输出类似 "#4e7a30" 的随机颜色
          this.drawLot(element.dataLotGPS, this.getRandomColor());
        });
      }, 1000)
    },
    getRandomColor () {
      let r = Math.floor(Math.random() * 256).toString(16);
      let g = Math.floor(Math.random() * 256).toString(16);
      let b = Math.floor(Math.random() * 256).toString(16);

      // 确保每个数字至少为两位数
      if (r.length == 1) r = '0' + r;
      if (g.length == 1) g = '0' + g;
      if (b.length == 1) b = '0' + b;

      return '#' + r + g + b;
    },
    async mapDialogShow () {
      this.mapDialog = new BMap.Map('mapDialog')// 创建Map实例
      // 初始化地图,设置中心点坐标和地图级别
      this.mapDialog.centerAndZoom(
        new BMap.Point(
          localStorage.getItem("LNG"),
          localStorage.getItem("LAT")
        ),
        16
      );
      this.mapDialog.enableScrollWheelZoom(true)//开启鼠标滚轮缩放
    },
    drawLot (dataLotGPS, color) {
      var points = []
      dataLotGPS.forEach(element => {
        points.push(new BMap.Point(element.LNG, element.LAT))
        this.dataViewport.push(new BMap.Point(element.LNG, element.LAT))
      });
      var polygon = new BMap.Polygon(points, {
        strokeColor: color,
        strokeWeight: 3,
        // strokeStyle: 'dashed',
        fillColor: color + '99'
      })
      this.mapDialog.addOverlay(polygon)
      this.mapDialog.setViewport(this.dataViewport);
    },
    // 导入Excel
    onChange (file, fileList) {
      //  console.log(fileList);
      this.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },
    // 读取数据
    readExcel (e) {
      let that = this;
      const files = that.fileData;
      console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      console.log(fileReader)
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          //  console.log(ev.target)
          //  console.log(this);
          const workbook = this.XLSX.read(data, {
            type: "binary"// 以字符编码的方式解析
          });

          if (workbook.SheetNames.length > 0) {
            workbook.SheetNames.forEach(element => {
              const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[element]); //生成json表格内容
              this.bulkLoad(ws)
            });

          } else {
            this.$message.error("未读取到表格内容");
          }
        } catch (e) {
          console.log(e)
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw);
    },
    bulkLoad (ws) {
      console.log(ws)
      var strLNG = '';
      var strLAT = '';
      ws.forEach(element => {
        strLNG += element.LNG + ','
        strLAT += element.LAT + ','
      });
      strLNG = strLNG.slice(0, strLNG.length - 1)
      strLAT = strLAT.slice(0, strLAT.length - 1)

      this.saveLotGPS(strLNG, strLAT);
    },
    // 保存GPS
    async saveLotGPS (strLNG, strLAT) {
      this.$axios({
        url: 'Worker/SaveLotGPSInfoPB',
        method: 'post',
        data: {
          LID: this.form.LID,
          LNAME: this.form.LNAME,
          LNGS: strLNG,
          LATS: strLAT,
        },
      }).then((res) => {
        console.log(res)
        // console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('编辑成功');
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('编辑失败');
        }
      })
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getData();
    },
    handleSizeChange (size) {
      this.pageSize = size;
      console.log(this.pageSize)
    }
  }
}
</script>
<style scoped lang='less'>
.content {
  overflow-y: scroll;
}
.el-col-6 {
  min-width: 400px;
  min-height: 50px;
}
.el-table th {
  height: 40px;
}
.new_person {
  .el-form {
    width: 300px;
    // height: 180px;
    margin: 10px auto;
    background-color: #dfe8f6;
    .el-form-item {
      margin-bottom: 20px;
    }
    .btns {
      display: flex;
      align-items: center;
      justify-content: center;
      // padding-top: 10px;
      .el-button {
        margin: 0 10px;
        /deep/span {
          padding: 0 5px;
        }
      }
    }
  }
}
.box {
  display: block;
  position: relative;
  height: 10vw;
  overflow: auto;
}
.marquee_list {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
}
.marquee_top {
  transition: all 1s;
  margin-top: -1.563vw;
}
.marquee_list li {
  height: 1.354vw;
  line-height: 1.354vw;
}
.marquee_list li span {
  padding: 0.26vw;
  font-size: 0.729vw;
}
</style>